package cn.ihelloworld.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.ihelloworld.bean.Catagory;
import cn.ihelloworld.dao.ICatagoryDao;
import cn.ihelloworld.dao.Pagation;

@Repository
public class CatagoryDaoImpl implements ICatagoryDao{
	
	@Autowired
	private SessionFactory sf;

	@Override
	public Catagory get(String id) {
		return (Catagory)sf.getCurrentSession().get(Catagory.class,id);
	}

	@Override
	public List<Catagory> select(Catagory t) {
		Criteria criteria=sf.getCurrentSession().createCriteria(Catagory.class);
		if(t!=null){
			if(t.getCode()!=null&&!t.getCode().equals("")){
				criteria.add(Restrictions.eq("code", t.getCode()));
			}
			if(t.getName()!=null&&!t.getName().equals("")){
				criteria.add(Restrictions.ilike("name", t.getName(),MatchMode.START));
			}
		}
		criteria.addOrder(Order.asc("turn"));;
		List<Catagory> list=criteria.list();
		return list;
	}

	@Override
	public Pagation<Catagory> selectForPage(Catagory t,int currentPage,int pageSize) {
		Pagation<Catagory> pagation=new Pagation<Catagory>();
		return pagation;
	}

	@Override
	public void saveOrUpdate(Catagory t) {
		sf.getCurrentSession().saveOrUpdate(t);
		
	}

	@Override
	public void delete(String id) {
		Catagory catagory=new Catagory();
		catagory.setCode(id);
		sf.getCurrentSession().delete(catagory);
	}

	@Override
	public void delete(String[] ids) {
		StringBuffer sb=new StringBuffer("delete Catagory where id in");
		sb.append("(");
		for(int i=0;i<ids.length;i++){
			sb.append("'");
			sb.append(ids[i]);
			sb.append("'");
			if(i!=ids.length-1){
				sb.append(",");
			}
		}
		sb.append(")");
		sf.getCurrentSession().createQuery(sb.toString()).executeUpdate();
	}

	@Override
	public List<Catagory> codeOrNameIn(String[] codes) {
		// TODO Auto-generated method stub
		Criteria criteria=sf.getCurrentSession().createCriteria(Catagory.class);
		criteria.add(Restrictions.or(Restrictions.in("code", codes), Restrictions.in("name", codes)));
		return criteria.list();
	}

}
